<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>axios基本使用</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
  </head>
  <body>
    <button>点击发送 GET 请求</button>
    <button>点击发送 GET 请求2</button>
    <button>点击发送 POST 请求</button>
    <button>点击发送 PUT 请求</button>
    <button>点击发送 DELETE 请求</button>

    <script>
      const buttons = document.querySelectorAll('button')

      // get请求
      buttons[0].onclick = () => {
        axios({
          method: 'GET',
          // url: 'http://localhost:3000/movie/2',
          url: 'http://localhost:3000/movie2',
          params: { // 自动转换为query参数
            id: 2,
            name: '大话西游'
          }
        }).then(
          response => { // 成功的value为response对象, data属性保存的是解析好js对象
            console.log(response.data)
          },
          error => {  // 失败的reason为error对象
            console.log(error)
            alert(error.message)
          }
        )
      }

       // async + await   非常非常重要
       /* 
       1. 在promise的左边加 await     => await表达式  => 它的结果为promise成功的value
       2. 在await所在的函数定义左侧加 async  => async函数
       3. 使用try...catch来得到异步失败的reason
       */
       buttons[1].onclick = async () => {
        try {
          // const response = await axios({
          //   method: 'GET',
          //   // url: 'http://localhost:3000/movie/2',
          //   url: 'http://localhost:3000/movie',
          //   params: { // 自动转换为query参数
          //     id: 2,
          //     name: '大话西游'
          //   }
          // })
          const response = await axios(`http://localhost:3000/movie?id=2&name=大话西游2`)
          console.log(response.data)
        } catch (error) {
          console.log(error)
          alert(error.message)
        }
      }

      // 添加
      buttons[2].onclick = async () => {
        const response = await axios({
          method: 'post',
          url: 'http://localhost:3000/movie',
          data: 'name=野外生存记&director=贝爷' // 并指定相应Content-Type请求头
        })
        console.log(response.data)
      }

      // 更新 
      buttons[3].onclick = async () => {
        const response = await axios({
          method: 'put',
          url: 'http://localhost:3000/movie/13',
          // data: 'name=野外生存记13&director=贝爷13'
          data: { // 内部会自动转换为Json, 并指定相应Content-Type请求头
            name: '野外生存记13',
            director: '贝爷13'
          }
        })
        console.log(response.data)
      }

      // 删除
      buttons[4].onclick = async () => {
        const response = await axios({
          method: 'delete',
          url: 'http://localhost:3000/movie/13',
        })
        console.log(response.data)
      }

    </script>
  </body>
</html>
